<script setup>
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import TabBar from './components/TabBar.vue'
import { useUserWebSocketStore } from './stores/websocket'

const route = useRoute()
const wsStore = useUserWebSocketStore()

// 消息通知相关
const notification = ref({
  show: false,
  message: '',
  type: 'success' // success, error, info
})
let notificationTimer = null

// 需要显示TabBar的主页面路径（只有这5个主Tab页面显示底部导航栏）
const showTabBarPaths = [
  '/',
  '/destination',
  '/orders',
  '/ai',
  '/profile'
]

// 判断是否应该显示TabBar：只有主Tab页面才显示（精确匹配）
const showTabBar = computed(() => {
  const currentPath = route.path.replace(/\/$/, '') || '/' // 移除末尾斜杠，空路径转为 '/'
  return showTabBarPaths.includes(currentPath)
})

// 显示通知消息
const showNotification = (message, type = 'success') => {
  // 清除之前的定时器
  if (notificationTimer) {
    clearTimeout(notificationTimer)
  }
  
  notification.value = {
    show: true,
    message: message,
    type: type
  }
  
  // 2.5秒后自动隐藏
  notificationTimer = setTimeout(() => {
    notification.value.show = false
    notificationTimer = null
  }, 2500)
}

// WebSocket 消息处理 - 监听身份认证结果
const handleIdentityMessage = (messageData) => {
  try {
    // 处理 OCR 识别结果
    if (messageData.type === 'ocr_complete') {
      console.log('App.vue: 收到身份认证成功消息:', messageData)
      // 显示顶部滑动通知
      showNotification('身份认证成功', 'success')
      // 更新本地存储的认证状态
      localStorage.setItem('user_verified', 'true')
      // 收到消息后关闭 WebSocket 连接
      wsStore.disconnectIdentityVerification()
      console.log('App.vue: 身份认证完成，已关闭 WebSocket 连接')
    }
  } catch (error) {
    console.error('App.vue: 处理身份认证消息失败:', error)
  }
}

// 注册实名认证消息处理器（不主动建立连接）
const registerIdentityHandler = () => {
  const userId = localStorage.getItem('user_id')
  if (!userId) {
    console.warn('App.vue: 用户未登录，跳过实名认证 WebSocket 监听注册')
    return
  }

  wsStore.registerIdentityMessageHandler('app', handleIdentityMessage)
}

onMounted(() => {
  registerIdentityHandler()
})

onUnmounted(() => {
  // 移除消息处理器（但不断开连接，因为可能还需要在其他页面接收消息）
  wsStore.unregisterIdentityMessageHandler('app')
  // 清除通知定时器
  if (notificationTimer) {
    clearTimeout(notificationTimer)
    notificationTimer = null
  }
})
</script>

<template>
  <div class="app-container">
    <!-- 顶部消息通知 -->
    <Transition name="slide-down">
      <div v-if="notification.show" :class="['notification', `notification-${notification.type}`]">
        <div class="notification-icon">
          <span v-if="notification.type === 'success'">✓</span>
          <span v-else-if="notification.type === 'error'">✕</span>
          <span v-else>ℹ</span>
        </div>
        <div class="notification-message">{{ notification.message }}</div>
      </div>
    </Transition>
    
    <RouterView />
    <TabBar v-if="showTabBar" />
  </div>
</template>

<style scoped>
.app-container {
  min-height: 100vh;
  background: #f5f5f5;
  position: relative;
}

/* 消息通知样式 */
.notification {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  min-height: 48px;
}

.notification-success {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  color: white;
}

.notification-error {
  background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
  color: white;
}

.notification-info {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  color: white;
}

.notification-icon {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
  margin-right: 12px;
  flex-shrink: 0;
}

.notification-message {
  flex: 1;
  font-size: 15px;
  font-weight: 500;
  line-height: 1.5;
}

/* 从上往下弹出的动画 */
.slide-down-enter-active {
  transition: all 0.3s ease-out;
}

.slide-down-leave-active {
  transition: all 0.3s ease-in;
}

.slide-down-enter-from {
  transform: translateY(-100%);
  opacity: 0;
}

.slide-down-enter-to {
  transform: translateY(0);
  opacity: 1;
}

.slide-down-leave-from {
  transform: translateY(0);
  opacity: 1;
}

.slide-down-leave-to {
  transform: translateY(-100%);
  opacity: 0;
}

/* 响应式适配 */
@media (max-width: 375px) {
  .notification {
    padding: 10px 12px;
    min-height: 44px;
  }
  
  .notification-icon {
    width: 20px;
    height: 20px;
    font-size: 12px;
    margin-right: 10px;
  }
  
  .notification-message {
    font-size: 14px;
  }
}
</style>
